/* eslint-disable react/jsx-key */
import React, { useState, useRef } from 'react';
import ReactDOM from 'react-dom';
import { Image, Alert, Button, Tooltip, Modal, message, Popconfirm } from 'antd';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { deletecompany, activity, store } from '@/services/business';
import { search } from '@/services/basic';
import { customer } from '@/services/customer';
import { area, classify, user } from '@/services/basic';
import { connect, history } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import ProDescriptions from '@ant-design/pro-descriptions';
import CompanyName from '@/components/CompanyName';
import moment from 'moment';

// type 类型有 table treeselect upload inputnumber datepicker daterange radio select textarea autoinput editor password input

let defaultFields = {
  snapshot: {
    value: null,
    type: 'recognition',
    title: '营业执照',
    name: ['snapshot'],
    required: false,
    col: { span: 24 },
  },
  name: {
    value: null,
    type: 'input',
    title: '公司全称',
    name: ['name'],
    required: true,
  },
  legal_person: {
    value: null,
    type: 'input',
    title: '公司法人',
    name: ['legal_person'],
    required: false,
  },
  address: {
    value: null,
    type: 'input',
    title: '公司地址',
    name: ['address'],
    required: false,
  },
  establish_date: {
    value: null,
    type: 'datepicker',
    title: '成立日期',
    name: ['establish_date'],
    format: 'YYYY-MM-DD',
    required: false,
    disabledDate: (current) => {
      return current && current > moment().endOf('day');
    },
    col: { span: 12 },
  },
  sign_date: {
    value: null,
    type: 'datepicker',
    title: '签约日期',
    name: ['sign_date'],
    format: 'YYYY-MM-DD',
    required: false,
    col: { span: 12 },
  },
  enterprise_credit_code: {
    value: null,
    type: 'input',
    title: '统一社会信用代码',
    name: ['enterprise_credit_code'],
    required: false,
  },
  customer_name: {
    value: null,
    type: 'input',
    title: '联系人',
    name: ['customer_name'],
    required: true,
  },
  customer_phone: {
    value: null,
    type: 'input',
    title: '联系人手机号',
    width: 120,
    name: ['customer_phone'],
    required: true,
  },
  area_id: {
    value: null,
    type: 'select',
    title: '区域',
    name: ['area_id'],
    required: true,
    linked: true,
    options: {
      database: area,
      params: { is_all: 1 },
    },
  },
  classify_id: {
    value: null,
    type: 'select',
    title: '公司类型',
    name: ['classify_id'],
    required: true,
    options: {
      database: classify,
      params: { is_all: 1 },
    },
  },
  promoter_user_id: {
    value: null,
    type: 'select',
    title: '促单人',
    name: ['promoter_user_id'],
    required: false,
    options: {
      database: user,
      params: { is_all: 1 },
    },
  },
  unit_price: {
    value: null,
    type: 'inputnumber',
    title: '月收费',
    name: ['unit_price'],
    required: true,
  },
  activity_id: {
    value: null,
    type: 'select',
    title: '活动',
    name: ['activity_id'],
    required: false,
    options: {
      database: activity,
      params: { is_all: 1 },
    },
    formart: ['id', 'content'],
  },
  is_create_order: {
    value: null,
    type: 'radio',
    title: '是否创建业务单',
    name: ['is_create_order'],
    required: true,
    options: [
      {
        label: '是',
        value: true,
      },
      {
        label: '否',
        value: false,
      },
    ],
  },
  is_accountant: {
    value: true,
    type: 'radio',
    title: '是否会计流程',
    name: ['is_accountant'],
    required: true,
    options: [
      {
        label: '是',
        value: true,
      },
      {
        label: '否',
        value: false,
      },
    ],
  },
  contracts: {
    value: null,
    type: 'upload',
    title: '合同协议',
    name: ['contracts'],
    required: true,
    listType: 'img',
    multiple: true,
    limit: 20,
    col: { span: 24 },
  },
  user_id: {
    value: null,
    type: 'select',
    title: '会计调度',
    name: ['user_id'],
    required: true,
    belinked: {
      options: {
        database: search,
        params: {
          is_all: 1,
          role_id: 13, //会计调度
          area_id: 'linked',
        },
      },
    },
    col: { span: 24 },
  },
};

let options = [
    {
      id: 'cache',
      name: '暂存',
    },
    {
      id: 'dispatch_refuse',
      name: '被拒绝',
    },
  ],
  valueEnum = {
    cache: {
      text: '暂存',
    },
    stalled: {
      text: '未开始',
    },
    dispatching: {
      text: '会计调度中',
    },
    dispatch_refuse: {
      text: '会计调度拒绝',
    },
    accounting: {
      text: '记账会计审核中',
    },
    account_refuse: {
      text: '记账会计拒绝',
    },
    account_cache: {
      text: '记账会计暂存',
    },
    completed: {
      text: '已完成',
    },
  };

function First(props) {
  const [vs, cvs] = useState(false), //表单显/隐
    [fields, cf] = useState(defaultFields),
    [iftype, ciftype] = useState({}),
    [sd, csd] = useState(false);

  let actionRef = useRef(),
    ChildRef = null;
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }
  const columns = [
    {
      title: '业务编号',
      dataIndex: 'code',
      key: 'code',
      search: false,
    },
    {
      title: '公司名称',
      width: 260,
      dataIndex: 'name',
      key: 'name',
      copyable: true,
      render: (_, row) => <CompanyName row={row} reload={reload} />,
    },
    {
      title: '公司法人',
      dataIndex: 'legal_person',
      key: 'legal_person',
      search: false,
      hideInTable: true,
    },
    {
      title: '公司地址',
      dataIndex: 'address',
      key: 'address',
      search: false,
      hideInTable: true,
    },
    {
      title: '成立日期',
      dataIndex: 'establish_date',
      key: 'establish_date',
      search: false,
      hideInTable: true,
      render: (text, row) => {
        return row?.establish_date ? moment(row.establish_date).format('YYYY-MM-DD') : '-';
      },
    },
    {
      title: '签约日期',
      dataIndex: 'sign_date',
      key: 'sign_date',
      search: false,
      hideInTable: true,
      render: (text, row) => {
        return row?.sign_date ? moment(row.sign_date).format('YYYY-MM-DD') : '-';
      },
    },
    {
      title: '统一社会信用代码',
      dataIndex: 'enterprise_credit_code',
      key: 'enterprise_credit_code',
      search: false,
      hideInTable: true,
    },
    {
      title: '公司营业执照',
      dataIndex: 'origin_url',
      key: 'origin_url',
      render: (_, row) => {
        return <Image width={32} height={32} style={{ padding: 2 }} src={row.origin_url} />;
      },
      hideInTable: true,
      search: false,
    },
    {
      title: '联系人',
      dataIndex: 'customer_name',
      key: 'customer_name',
      ellipsis: true,
    },
    {
      title: '联系人手机号',
      width: 120,
      dataIndex: 'customer_phone',
      key: 'customer_phone',
      render: (_, row) => (
        <Tooltip title={row.customer_phone}>
          <a href={`tel:${row.customer_phone}`} className="oneline">
            {row.customer_phone}
          </a>
        </Tooltip>
      ),
    },
    {
      title: '区域名称',
      dataIndex: 'area_name',
      key: 'area_name',
      search: false,
    },
    {
      title: '区域编码',
      dataIndex: 'area_code',
      key: 'area_code',
      search: false,
      hideInTable: true,
    },
    {
      title: '接单人',
      dataIndex: 'user_name',
      key: 'user_name',
      search: false,
    },
    {
      title: '促单人',
      dataIndex: 'promoter_user_name',
      key: 'promoter_user_name',
      search: false,
    },
    {
      title: '公司类型',
      dataIndex: 'classify_name',
      key: 'classify_name',
      search: false,
    },
    {
      title: '月收费',
      dataIndex: 'unit_price',
      key: 'unit_price',
      search: false,
    },
    {
      title: '活动',
      dataIndex: 'activity_content',
      key: 'activity_content',
      search: false,
      hideInTable: true,
    },
    {
      title: '业务续单',
      dataIndex: 'is_create_order',
      key: 'is_create_order',
      search: false,
      render: (_, row) => <span>{row.is_create_order ? '是' : '否'}</span>,
    },
    {
      title: '会计流程',
      dataIndex: 'is_accountant',
      key: 'is_accountant',
      search: false,
      render: (_, row) => <span>{row.is_accountant ? '是' : '否'}</span>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      valueType: 'select',
      options: options,
      valueEnum: valueEnum,
      width: 120,
      render: (_, row) => (
        <div
          className="oneline"
          style={{
            color: row?.status?.indexOf('refuse') != -1 ? 'red' : 'auto',
            cursor: 'pointer',
          }}
          onClick={() => {
            if (row?.status?.indexOf('refuse') != -1) {
              Modal.info({
                title: '拒绝原因',
                content: row.dispatch_refuse_message,
                maskClosable: true,
              });
            }
          }}
        >
          {valueEnum[row.status]?.text}
        </div>
      ),
    },
    {
      title: '合同协议',
      dataIndex: 'contracts',
      key: 'contracts',
      search: false,
      render: (_, row) => {
        if (!row.contracts) {
          return (
            <Image
              width={32}
              height={32}
              style={{ padding: 2 }}
              src={require('@/assets/default.png')}
            />
          );
        } else {
          return row.contracts.map((it) => {
            return <Image width={32} height={32} src={it.origin_url} style={{ padding: 2 }} />;
          });
        }
      },
      hideInTable: true,
    },
    {
      title: '收款单',
      dataIndex: 'id',
      key: 'id',
      search: false,
      render: (_, row) => (
        <a
          style={{ color: '#f50' }}
          onClick={() => {
            ciftype({
              ...iftype,
              val: 'skd',
              title: '收款单',
              curitem: row,
            });
            cvs(true);
          }}
        >
          查看
        </a>
      ),
    },
    {
      title: '操作',
      valueType: 'option',
      width: 100,
      render: (text, record, _, action) => [
        // <a onClick={() => {
        //     history.push({
        //         pathname: `/finance/receipt`,
        //         query: {
        //             id: record.id,
        //         }
        //     })
        // }}>
        //     新增收款单
        // </a>,
        <a
          disabled={!options.some((it) => it.id == record.status)}
          style={{ color: !options.some((it) => it.id == record.status) ? '#999' : '#1890ff' }}
          onClick={() => {
            if (!options.some((it) => it.id == record.status)) {
              return;
            }
            cvs(true);
            cf((fields) => {
              for (let i in fields) {
                fields[i].value = record[i];
                if (i == 'snapshot') {
                  fields[i].value = {
                    origin_url: record.origin_url,
                    preview_url: record.preview_url,
                  };
                }
                if (i == 'user_id') {
                  fields[i].value = record.promoter_user_id;
                }
              }
              return { ...fields };
            });
            ciftype({
              val: 'edit',
              title: '编辑业务',
              id: record.id,
              type: record.status,
            });
          }}
        >
          编辑
        </a>,
        <Popconfirm
          placement="bottom"
          title={'确认删除该业务？'}
          onConfirm={() => {
            deletecompany(record.id).then((res) => {
              if (res.code == 0) {
                message.success('操作成功');
                reload();
              }
            });
          }}
          okText="删除"
          disabled={!options.some((it) => it.id == record.status)}
          cancelText="取消"
        >
          <a
            disabled={!options.some((it) => it.id == record.status)}
            style={{ color: !options.some((it) => it.id == record.status) ? '#999' : '#f50' }}
          >
            删除
          </a>
        </Popconfirm>,
      ],
    },
  ];

  let extrarender = [
    <div
      className="action"
      title="新增"
      onClick={() => {
        cvs(true);
        cf((fields) => {
          for (let i in fields) {
            fields[i].value = null;
            if (i == 'is_accountant') {
              fields[i].value = true;
            }
            if (i == 'is_create_order') {
              fields[i].value = false;
            }
          }
          return { ...fields };
        });
        ciftype({
          val: 'add',
          title: '新增业务',
        });
      }}
    >
      <PlusOutlined />
    </div>,
  ];

  let saveData = (values) => {
    let { dispatch } = props;
    values = {
      ...values,
      ...values.snapshot,
    };

    if (iftype.val == 'add') {
      dispatch({
        type: 'business/addcompany',
        payload: values,
      }).then((res) => {
        if (res.code == 0) {
          Modal.confirm({
            title: '操作成功',
            content: '是否立刻新增收款单？',
            okText: '是',
            cancelText: '否',
            onOk: () => {
              history.push({
                pathname: `/finance/receipt`,
                query: {
                  id: res?.data?.id,
                  service_type: 'account',
                },
              });
            },
            onCancel: () => {
              reload();
              cvs(false);
            },
          });
        }
      });
    } else if (iftype.val == 'edit') {
      dispatch({
        type: iftype.type == 'dispatch_refuse' ? 'business/dispatchretry' : 'business/addcompany',
        payload: { ...values, id: iftype.id },
      }).then((res) => {
        if (res.code == 0 && iftype.type != 'dispatch_refuse') {
          Modal.confirm({
            title: '操作成功',
            content: '是否立刻新增收款单？',
            okText: '是',
            cancelText: '否',
            onOk: () => {
              history.push('/finance/receipt');
            },
            onCancel: () => {
              reload();
              cvs(false);
            },
          });
        } else {
          reload();
          cvs(false);
        }
      });
    }
  };

  return (
    <div>
      <AutoTable
        bordered={false}
        pagetitle={
          <span>
            代账业务{' '}
            <a
              style={{ fontSize: 14, paddingLeft: 12 }}
              onClick={() => {
                props.close();
              }}
            >
              {' '}
              返回
            </a>
          </span>
        } //页面标题
        pageextra={extrarender} //页面操作 新增or批量删除
        columns={columns}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        path="/wbn-api/company"
        extraparams={{ type: 0, service_type: 'account', is_limit: 1 }}
        //withCard={false}
        //cardtitle = "name" //卡片标题
        //cardavatar = "img_url" //卡片头像
      />
      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={false}
        width={1400}
        destroyOnClose={true}
        style={{ top: 20 }}
      >
        {iftype.val == 'skd' ? (
          <div>
            <Alert
              message="显示/隐藏代账公司详情"
              style={{ marginBottom: 20 }}
              showIcon
              type="info"
              action={
                <Button
                  size="small"
                  type="primary"
                  onClick={() => {
                    csd(!sd);
                  }}
                >
                  {!sd ? '显示' : '隐藏'}
                </Button>
              }
            />
            <div
              style={{
                backgroundColor: '#f9f9f9',
                padding: sd ? 12 : 0,
                paddingBottom: 0,
                borderRadius: 8,
                height: sd ? 'auto' : 0,
                transition: 'all 0.4s',
                overflow: 'hidden',
              }}
            >
              <ProDescriptions
                title={`${iftype.curitem.name}的详细信息`}
                columns={[...columns.filter((it) => it.key != 'user_name')]}
                column={{ xs: 1, sm: 1, md: 2, lg: 3, xl: 4, xxl: 5 }}
                dataSource={iftype.curitem}
              />
            </div>
            <AutoTable
              columns={[
                {
                  title: '本期收费单号',
                  dataIndex: 'settle_id',
                  key: 'settle_id',
                  width: 100,
                  copyable: true,
                  search: false,
                  render: (_, row) => (
                    <span>
                      {row.settle_id ? (Array(5).join(0) + row.settle_id).slice(-5) : '-'}
                    </span>
                  ),
                },
                {
                  title: '公司名称',
                  width: 260,
                  dataIndex: 'company_name',
                  key: 'company_name',
                  copyable: true,
                },
                {
                  title: '应收款',
                  dataIndex: 'receivable',
                  key: 'receivable',
                  search: false,
                },
                {
                  title: '月收费',
                  dataIndex: 'unit_price',
                  key: 'unit_price',
                  search: false,
                },
                {
                  title: '服务开始时间',
                  dataIndex: 'service_start_time',
                  key: 'service_start_time',
                  width: 100,
                  search: false,
                },
                {
                  title: '服务结束时间',
                  dataIndex: 'service_end_time',
                  key: 'service_end_time',
                  width: 100,
                  search: false,
                },
                {
                  title: '接单人',
                  dataIndex: 'user_name',
                  key: 'user_name',
                  search: false,
                },
                {
                  title: '支付周期',
                  dataIndex: 'payment_cycle_name',
                  key: 'payment_cycle_name',
                  search: false,
                },
                {
                  title: '周期月数',
                  dataIndex: 'cycle_num',
                  key: 'cycle_num',
                  search: false,
                },
                {
                  title: '支付类型',
                  dataIndex: 'payment_type',
                  key: 'payment_type',
                  valueType: 'select',
                  options: [
                    {
                      id: 'full',
                      name: '全款',
                    },
                    {
                      id: 'deposit',
                      name: '定金',
                    },
                    {
                      id: 'balance',
                      name: '尾款',
                    },
                  ],
                  valueEnum: {
                    full: {
                      text: '全款',
                    },
                    deposit: {
                      text: '定金',
                    },
                    balance: {
                      text: '尾款',
                    },
                  },
                },
                {
                  title: '收款日期',
                  dataIndex: 'payment_time',
                  key: 'payment_time',
                  width: 100,
                },
                {
                  title: '实际收款',
                  dataIndex: 'actual_receive',
                  key: 'actual_receive',
                },
                {
                  title: '收款方式',
                  dataIndex: 'payment_name',
                  key: 'payment_name',
                },
                {
                  title: '备注',
                  dataIndex: 'remark',
                  key: 'remark',
                  search: false,
                },
                {
                  title: '状态',
                  dataIndex: 'status',
                  key: 'status',
                  valueType: 'select',
                  options: [
                    {
                      id: 'cashiering',
                      name: '出纳审核中',
                    },
                    {
                      id: 'cashier_refuse',
                      name: '出纳拒绝',
                    },
                    {
                      id: 'cache',
                      name: '待激活',
                    },
                  ],
                  valueEnum: {
                    cache: {
                      text: '待激活',
                      status: 'error',
                    },
                    cashiering: {
                      text: '出纳审核中',
                    },
                    cashier_refuse: {
                      text: '出纳拒绝',
                    },
                    accounting: {
                      text: '会计审核中',
                    },
                    account_refuse: {
                      text: '会计拒绝',
                    },
                    completed: {
                      text: '已完成',
                    },
                  },
                  render: (dom, row) => (
                    <div
                      style={{
                        color: row?.status?.indexOf('refuse') != -1 ? 'red' : 'auto',
                        cursor: 'pointer',
                      }}
                      onClick={() => {
                        if (row.status == 'cashier_refuse') {
                          Modal.info({
                            title: '拒绝原因',
                            content: row.cashier_refuse_message,
                            maskClosable: true,
                          });
                        }
                      }}
                    >
                      {dom}
                    </div>
                  ),
                },
              ]}
              path="/wbn-api/payment_order"
              extraparams={{ company_id: iftype.curitem.id }}
              withCard={false}
              //cardtitle = "name" //卡片标题
              //cardavatar = "img_url" //卡片头像
            />
          </div>
        ) : iftype.val == 'see' && iftype.curitem ? (
          <ProDescriptions
            title={`${iftype.curitem.name}的详细信息`}
            columns={[...columns]}
            column={{ xs: 1, sm: 1, md: 2, lg: 3, xl: 4, xxl: 5 }}
            dataSource={iftype.curitem}
          />
        ) : (
          <InitForm
            fields={fields}
            submitData={(values) => {
              saveData(values);
            }}
            onChange={(changedValues, allValues) => {
              //联动操作
            }}
            submitting={
              props.loading.effects['business/dispatchretry'] ||
              props.loading.effects['business/addcompany'] ||
              !vs
            }
            halfsave={true}
          />
        )}
      </Modal>
    </div>
  );
}

export default connect(({ business, loading }) => ({
  business,
  loading,
}))(First);
